package com.sduonline.isdapp.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sduonline.isdapp.config.AutoServiceTriggerConfig;
import com.sduonline.isdapp.other.AutoServletTrigger;
import com.sduonline.isdapp.service.AutoService;

/**
 * Servlet implementation class AutoServlet
 */
@WebServlet("/AutoServlet")
public class AutoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

	public AutoServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		// startTime and endTime
		String st = request.getParameter("st");
		String et = request.getParameter("et");

		PrintWriter pw = new PrintWriter(response.getOutputStream());

		try {
			if (st != null && !"".equals(st) && et != null && !"".equals(et)) {
				// 自己用的servlet
				new AutoService().visitArticlesWithinTime(st, et);
			}
			pw.write("success");
		} catch (Exception e) {
			e.printStackTrace();
			pw.write("failed");
		}

		pw.flush();
		pw.close();

	}

	@Override
	public void init() {
		new AutoService().start();// 启动一直访问近两天的文章的线程
		System.out.println(AutoServiceTriggerConfig.isOpenAutoParser);
		if (AutoServiceTriggerConfig.isOpenAutoParser) {
			new AutoServletTrigger().startAutoVisitThread();// 启动访问过去到当前时间的线程
		}
		System.out.println("init AutoService and Thread start...");
	}

	@Override
	public void destroy() {
		new AutoService().stop();
		new AutoServletTrigger().stopAutoVisitThread();
		System.out.println("stop AutoService and Thread stop...");
	}

}
